package com.mindframe.pruebasthread;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

public class ThreadsActivity extends Activity {
	
	
	Intent intent = new Intent();
	private static final int TAKE_PHOTO_CODE = 1;
	private static final int SELECT_PICTURE = 2;
	Uri imgSelected;
	Button btnFoto;
	
	File file;
	Bitmap photo;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		getWindowManager().getDefaultDisplay().getHeight();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_threads);
		
		Log.d("Metodo:", "Entramos:");
		
		
	
		btnFoto = (Button)findViewById(R.id.btnFoto);
		
		btnFoto.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
				startActivityForResult(intent, SELECT_PICTURE);
			}
		});
		
		
				
		
//		setContentView(new Panel(this));
	}
	 
	@Override
	public void onActivityResult(int requestCode, int resultCode,Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("Método", "onActivityResult");
		
		imgSelected = data.getData();
		
		BitmapFactory.Options bmfOpt = new BitmapFactory.Options();
	    bmfOpt.inPreferredConfig = Bitmap.Config.RGB_565;
		
		InputStream is;
		try {
			is = getContentResolver().openInputStream(imgSelected);
			BufferedInputStream bis = new BufferedInputStream(is);
			photo = BitmapFactory.decodeStream(bis, new Rect(), bmfOpt);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		setContentView(new Panel(this, photo));
		
		
	}
	
}
class Panel extends SurfaceView implements SurfaceHolder.Callback {


	private static final int MAXNUMFACES = 10;
	private static final int SPEED = 5;
	
	private FaceDetector detector;
	private Face[] faces;
	List<PointF> eyeList;
	PointF puntoGafas;
	Bitmap gafas, imgBackg, dealText;
	int w_backg, h_backg, facesFound, w_screen, h_screen;
	int dynamic_y = 0;
	
	List<Glasses> glassesList = new ArrayList<Glasses>();
	Glasses currentGlasses;
	boolean cont = true;
	
	Paint paint = new Paint();
	
	Thread thread;
	
	SurfaceHolder holder;

	public Panel(Context context, Bitmap photo) {
		super(context);
		
		Log.d("Metodo:", "Constructor");
		holder = getHolder();
		holder.addCallback(this);
		thread = new ThreadPrincipal(holder, this);
		imgBackg = photo;
		
		
		
	}
	
	public void populateGlasses(){
		

//	    imgBackg = BitmapFactory.decodeResource(getResources(), R.drawable.fotocara, bmfOpt);
		
		w_screen = holder.getSurfaceFrame().right;
		h_screen = holder.getSurfaceFrame().bottom;
		
		dealText = BitmapFactory.decodeResource(getResources(), R.drawable.dealtext);
		dealText = resizeBitmap(w_screen/2, dealText);
		
		
		imgBackg = resizeBitmap(w_screen, imgBackg);
		
		w_backg = imgBackg.getWidth();
		h_backg = imgBackg.getHeight();
		
		faces = new FaceDetector.Face[MAXNUMFACES];
		detector = new FaceDetector(w_backg, h_backg, MAXNUMFACES);
		facesFound = detector.findFaces(imgBackg, faces);
		
		
		
		for(int i = 0; i <= faces.length-1; i++){
			if(faces[i] != null){
				Glasses glasses = new Glasses();
				PointF center = new PointF();
				faces[i].getMidPoint(center);
				glasses.pos_x = (int) (center.x - faces[i].eyesDistance());
				glasses.pos_y = (int) (center.y - faces[i].eyesDistance()/4);
				glasses.distance = faces[i].eyesDistance();
				glasses.glasses = resizeGlasses(faces[i].eyesDistance());
				glasses.num=String.valueOf(i);
				glassesList.add(glasses);
			}
		}
	}

	@Override
	public void onDraw(Canvas canvas) {
		Log.d("Metodo:", "onDraw");
		canvas.drawBitmap(imgBackg, 0,0, paint);
		for(Glasses glasses: glassesList){
			currentGlasses = glasses;
			if(currentGlasses != null){
				canvas.drawBitmap(currentGlasses.glasses, currentGlasses.pos_x, currentGlasses.dynamic_y, null);
			}
		}
		canvas.drawBitmap(dealText, (w_backg - dealText.getWidth())/2, h_backg-60, paint);
		
		
	}
	
	public boolean contThread(){
		
		if(currentGlasses != null){
			Glasses lastGlasses = glassesList.get(glassesList.size()-1);
			if(currentGlasses.equals(lastGlasses)){
				if(currentGlasses.dynamic_y >= lastGlasses.pos_y-SPEED){
					cont = false;
				}
			}
		}
		
		return cont;
		
	}
	
	public void animateGlasses(){
		Log.d("Metodo:", "animateGlasses");
		for(Glasses glasses: glassesList){
			currentGlasses = glasses;
			if(currentGlasses != null){
				if(currentGlasses.dynamic_y <= currentGlasses.pos_y){
					currentGlasses.dynamic_y+=SPEED;
				}
			}
		}
	}
	
	public Bitmap resizeGlasses(float distance){
		
    	Bitmap gafasOrig = BitmapFactory.decodeResource(getResources(),R.drawable.glasses2);
    	
    	int w_gafOrig = gafasOrig.getWidth();
    	int h_gafOrig = gafasOrig.getHeight();
    	
    	float w_escala = distance*2;
    	float h_escala = h_gafOrig * distance / w_gafOrig*2;
	
    	return Bitmap.createScaledBitmap(gafasOrig, (int)w_escala, (int)h_escala, true); 
    	
    	
    }
	
	 public Bitmap resizeBitmap(float newWidth, Bitmap img){
	    	
	    	float w_img = img.getWidth();
	    	float h_img = img.getHeight();
	    	
	    	float newHeight = h_img * newWidth /w_img;
	    	
	    	
	    	return Bitmap.createScaledBitmap(img, (int)newWidth, (int)newHeight, true); 
	    	
	    }
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.d("Metodo:", "surfaceChanged");

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.d("Metodo:", "surfaceCreated");
		populateGlasses();
		thread.start();

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.d("Metodo:", "surfaceDestroyed");
		boolean retry = true;
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
				Log.d("exc", e.getMessage());
			}
		}
	}

	class ThreadPrincipal extends Thread {
		private SurfaceHolder _surfaceHolder;
		boolean running = true;
		Panel _panel;

		public ThreadPrincipal(SurfaceHolder surfaceHolder, Panel panel) {
			Log.d("Metodo:", "ConstructorThread");
			_surfaceHolder = surfaceHolder;
			_panel = panel;

		}
		

		@Override
		public void run() {
			Log.d("Metodo:", "ThreadRun");
			Canvas c = null;
			while (_panel.contThread()) {

				try {
					c = _surfaceHolder.lockCanvas();
					synchronized (_surfaceHolder) {
						_panel.animateGlasses();
						_panel.onDraw(c);
					}
				} finally {
					if (c != null)
						_surfaceHolder.unlockCanvasAndPost(c);
				}
			}

		}
	}
}